angular.module('easego.services', ['ngCordova'])
.constant('appConfig',{
  "rootUrl": 'http://192.168.1.80:3000',
  "isPC": navigator.platform=="Win32"
})

.constant('productCategories',{
  classic: "经典",
  honeymoon:"蜜月",
  kid: "亲子",
  family: "家庭"
})

.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
      return JSON.parse($window.localStorage[key] || '{}');
    }
  }
}])

.factory('UtilService',function UtilService(){
  return {
    dateDiff: function (toDate, fromDate) {
      var magicNumber = (1000 * 60 * 60 * 24);
      if(toDate && fromDate){
        var dayDiff = Math.floor((toDate - fromDate) / magicNumber);
        if (angular.isNumber(dayDiff)){
          return dayDiff + 1;
        }
      }
    }
  };
})

.factory('ArticleService',
['$http','$httpParamSerializerJQLike','$q','appConfig',
function ArticleService($http,$httpParamSerializerJQLike,$q,appConfig) {
  return {
    list: function(pageNo){
      return $http.get(
        appConfig.rootUrl + "/api/v1/articles/list/" + (pageNo||0));
    },
    query: function(articleId){
      return $http.get(
        appConfig.rootUrl + "/api/v1/articles/query/" + articleId);
    },
    addComment: function(userLogonName, userPassword, articleId, sectionId, text, commenterId){
      return $http.post(
        appConfig.rootUrl + "/api/v1/articles/addComment",
        $httpParamSerializerJQLike({userLogonName:userLogonName,userPassword:userPassword,
        articleId: articleId, sectionId: sectionId, text: text, commenterId: commenterId}),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
    addLike: function(userLogonName, userPassword, articleId, sectionId, likerId){
      return $http.post(
        appConfig.rootUrl + "/api/v1/articles/addLike",
        $httpParamSerializerJQLike({userLogonName:userLogonName,userPassword:userPassword,
        articleId: articleId, sectionId: sectionId, likerId: likerId}),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
    newArticle: function(userLogonName, userPassword, name, 
    geolocationSpot, location, authorId){
      return $http.post(
        appConfig.rootUrl + "/api/v1/articles/newArticle",
        $httpParamSerializerJQLike({userLogonName:userLogonName, 
          userPassword:userPassword,
          name: name, 
          geolocationSpot: geolocationSpot, 
          location: location, 
          authorId: authorId}),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },

    addArticleSectionImage: function(userLogonName, userPassword,
    articleId,imagePathName){
      var sectionId;
      var defered = $q.defer();
      function uploadComplete(evt) {
        sectionId = JSON.parse(evt.target.responseText)._id;
        defered.resolve(sectionId);
      }
      function uploadFailed(evt) {
        defered.reject(evt);
      };
      var formData = new FormData();
      formData.append("articleId", articleId);
      formData.append("file", imagePathName);

      var xhr = new XMLHttpRequest()

      xhr.addEventListener("load", uploadComplete, false);
      xhr.addEventListener("error", uploadFailed, false);
      xhr.open("POST", appConfig.rootUrl + "/api/v1/articles/newPhoto");
      xhr.setRequestHeader("Accept", "application/json");
      xhr.send(formData);

      return defered.promise;
    },

    addArticleSectionImageBase64: function(
    userLogonName, userPassword,articleId,data){
      return $http.post(
        appConfig.rootUrl + "/api/v1/articles/newPhoto",
        {userLogonName:userLogonName,userPassword:userPassword,
        articleId: articleId, file: data}
      );
    },

    updateSection: function(userLogonName, userPassword,articleId,sectionId,
    text,date,imageFileName,isArticleCoverImage){
      return $http.post(
        appConfig.rootUrl + "/api/v1/articles/updateSection",
        $httpParamSerializerJQLike({userLogonName:userLogonName,userPassword:userPassword,
        articleId: articleId, sectionId: sectionId, text: text, date: date, 
        isArticleCoverImage: isArticleCoverImage ? 1 : 0 ,imageFileName: imageFileName,}),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },

    listOfAuthor: function(userId){
      return $http.get(
        appConfig.rootUrl + "/api/v1/articles/listOfAuthor/" + userId);
    },

    updateArticle: function(userLogonName, userPassword,articleId,
    name,geolocationSpot,location,startDate,mileage,state,publicity){
      return $http.put(
        appConfig.rootUrl + "/api/v1/articles/updateArticle",
        $httpParamSerializerJQLike({userLogonName:userLogonName,userPassword:userPassword,
        articleId: articleId, name: name,geolocationSpot: geolocationSpot,
        location:location,startDate: startDate,mileage: mileage,
        state: state,publicity: publicity,}),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
  };
}])

.factory('ProductService',
['$http','$httpParamSerializerJQLike','appConfig',
function ProductService($http,$httpParamSerializerJQLike,appConfig) {
  return {
    list: function(category){
      return $http.get(
        appConfig.rootUrl + "/api/v1/products/list/" + (category || ""));
    },
  };
}])

.factory('PoService',
['$http','$httpParamSerializerJQLike','appConfig',
function PoService($http,$httpParamSerializerJQLike,appConfig) {
  return {
    list: function(userLogonName, userPassword,userId){
      return $http.post(
        appConfig.rootUrl + "/api/v1/pos/list/",
        $httpParamSerializerJQLike(
          {userLogonName: userLogonName,userPassword: userPassword,userId: userId}),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
    newPo: function(userLogonName, userPassword, productId, userId,
    amount,useDate,contactName,contactPhone,contactEmail){
      return $http.post(
        appConfig.rootUrl + "/api/v1/pos/newPo",
        $httpParamSerializerJQLike(
          { userLogonName:userLogonName, userPassword:userPassword,
            userId: userId, productId: productId, amount: amount,
            useDate: useDate, contactName: contactName, 
            contactPhone: contactPhone, contactEmail: contactEmail
          }
        ),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    },
  };
}])

.factory('LogonService',['$http','$httpParamSerializerJQLike','appConfig',
function LogonService($http,$httpParamSerializerJQLike,appConfig) {
  return {
    logon: function(userLogonName,password){
      return $http.post(
        appConfig.rootUrl + "/api/v1/users/logon",
        $httpParamSerializerJQLike({userLogonName:userLogonName,userPassword:password}),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    },
  };
}])

.factory('RegisterService',['$http','$httpParamSerializerJQLike','appConfig',
function RegisterService($http,$httpParamSerializerJQLike,appConfig) {
  return {
    getVerificationCode: function(mobile){
      return $http.post(
        appConfig.rootUrl + "/api/v1/users/get-verification-code",
        $httpParamSerializerJQLike({
          mobile: mobile,
        }),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
    register: function(logonName,password,mobile,name,verifyCode){
      return $http.post(
        appConfig.rootUrl + "/api/v1/users/register",
        $httpParamSerializerJQLike({
          logonName: logonName,
          password: password,
          name: name,
          mobile: mobile,
          verifyCode: verifyCode,
        }),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
  };
}])

.factory('UserService',['$http','$httpParamSerializerJQLike','$q','appConfig',
function UserService($http,$httpParamSerializerJQLike,$q,appConfig) {
  return {
    updateUserImage: function(userLogonName, userPassword,userId,imagePathName){
      var defered = $q.defer();
      function uploadComplete(evt) {
        var user = JSON.parse(evt.target.responseText);
        defered.resolve(user);
      }
      function uploadFailed(evt) {
        defered.reject(evt);
      };
      var formData = new FormData();
      formData.append("userId", userId);
      formData.append("file", imagePathName);

      var xhr = new XMLHttpRequest()

      xhr.addEventListener("load", uploadComplete, false);
      xhr.addEventListener("error", uploadFailed, false);
      xhr.open("POST", appConfig.rootUrl + "/api/v1/users/updateUserImage");
      xhr.setRequestHeader("Accept", "application/json");
      xhr.send(formData);

      return defered.promise;
    },
    updateAccountSetting: function(userLogonName, userPassword,userId,
    name,mobile,email,gender,introduction){
      return $http.post(
        appConfig.rootUrl + "/api/v1/users/updateAccountSetting",
        $httpParamSerializerJQLike({
          userLogonName: userLogonName,
          userPassword: userPassword,
          userId: userId,
          name: name,
          mobile: mobile,
          email: email,
          gender: gender,
          introduction: introduction,
        }),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
    changePassword: function(userLogonName, userPassword,userId,password){
      return $http.put(
        appConfig.rootUrl + "/api/v1/users/changePassword",
        $httpParamSerializerJQLike({
          userLogonName: userLogonName,
          userPassword: userPassword,
          userId: userId,
          password: password,
        }),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
      );
    },
  };
}])

;
